package com.hmall.service;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.util.BigDecimalUtil;
import com.hdmall.business.common.util.DecimalFormatUtrils;
import com.hdmall.business.common.util.PropertiesUtil;
import com.hmall.mapper.MallCartMapper;
import com.hmall.mapper.MallOrderItemMapper;
import com.hmall.mapper.MallPriceMapper;
import com.hmall.mapper.MallProductMapper;
import com.hmall.model.MallCart;
import com.hmall.model.MallOrderItem;
import com.hmall.model.MallPrice;
import com.hmall.model.MallProduct;
import com.hmall.vo.CartProductVo;
import com.hmall.vo.CartTemVo;
import com.hmall.vo.CartVo;
import com.hmall.vo.ShopVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class CartService {

    private final static int CHECK = 1;

    private final static int UN_CHECK = 0;

    @Autowired
    private MallCartMapper cartMapper;

    @Autowired
    private MallProductMapper productMapper;

    @Autowired
    private MallPriceMapper mallPriceMapper;

    @Autowired
    private MallOrderItemMapper mallOrderItemMapper;


    public ServerResponse add(Integer userId, Integer productId, String grade, BigDecimal weight) {
        MallPrice mallPrice = mallPriceMapper.selectPriceNum(productId, weight, grade);
        if (mallPrice == null || grade.equals("")) {
            //设置默认等级
            try {
                grade = cartMapper.selectGradeMaxPrice(productId);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(), ResponseCode.SHOP_NOT_FOUND.getDesc(), null);
            }
        }

        //得到cart
        CartProductVo cart = cartMapper.selectCartByUserIdProductId(userId, productId, grade);
        if (cart == null) {
            //这个产品不在这个购物车里,需要新增一个这个产品的记录

            MallCart cartItem = new MallCart();
            cartItem.setWeight(weight);
            cartItem.setChecked(Const.Cart.CHECKED);
            cartItem.setGrade(grade);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            cartItem.setCreateTime(new Date());
            //产品id查询商家id
            Integer shopId = null;
            try {
                shopId = productMapper.selectShopIdByProductId(productId);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(), ResponseCode.SHOP_NOT_FOUND.getDesc(), null);
            }
            if (null == shopId) {
                return ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(), ResponseCode.SHOP_NOT_FOUND.getDesc(), null);
            }
            cartItem.setShopId(shopId);
            cartMapper.insert(cartItem);
        } else {
            //这个产品已经在购物车里了.
            //如果产品已存在,数量相加
//            weight = cart.getWeight().add(weight);
//            cart.setWeight(weight);
//            cartMapper.updateCartOnlyWeight(cart);
            cartMapper.updateCartOnlyWeight(cart, weight);
        }

        return ServerResponse.createBySuccess();
    }

    public ServerResponse<CartTemVo> update(Integer userId, Integer cartId, BigDecimal weight) {
        if (cartId == null || weight == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //根据productId获得当前产品的购物车属性
        MallCart cart = cartMapper.selectByPrimaryKey(cartId);

        if (cart != null) {
            cart.setWeight(weight);
        }
        cartMapper.updateByPrimaryKey(cart);
        System.out.println(cart);
        return selectCartProducts(userId);
    }

    //根据用户id 等级 产品等 查询购物车id
    public ServerResponse selectCartIdByGrdWtPrUsr(Integer userId, Integer productId, BigDecimal weight, String grade) {
        Integer cartId = 0;
        try {
            cartId = cartMapper.selectCartIdByGrdWtPrUsr(userId, productId, weight, grade);
        } catch (Exception e) {
            e.printStackTrace();
            ServerResponse.createByStatus(300, "根据用户id 等级产品等查询购物车id失败", "");
        }
        if (null == cartId) {
            ServerResponse.createByStatus(300, "购物车没有此产品", "");
        }
        return ServerResponse.createBySuccess(cartId);

    }

    public ServerResponse<CartTemVo> deleteProduct(Integer userId, String cartIds) {
        List<String> cartIdList = Splitter.on(",").splitToList(cartIds);
        if (CollectionUtils.isEmpty(cartIdList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdcartIds(userId, cartIdList);
        List<CartProductVo> productVos = cartMapper.selectCartByUserId(userId);
        CartTemVo cartTem = new CartTemVo();
        if (productVos == null || productVos.size() == 0) {
            return ServerResponse.createBySuccess(cartTem);
        }
        return selectCartProducts(userId);
    }

    //列出已经选中的产品列表
    public ServerResponse<CartVo> listCheck(Integer userId) {
        CartVo cartVo = this.getCartVoLimit(userId, CHECK).getData();
        return ServerResponse.createBySuccess(cartVo);
    }

    //列出所有购物车列表
    public ServerResponse<CartVo> list(Integer userId) {

        CartVo cartVo = this.getCartVoLimit(userId, UN_CHECK).getData();
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartTemVo> selectOrUnSelect(Integer userId, Integer cartId, Integer checked) {
        cartMapper.checkedOrUncheckedProduct(userId, cartId, checked);
        return selectCartProducts(userId);
    }

    public ServerResponse<Integer> getCartProductCount(Integer userId) {
        if (userId == null) {
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
    }

    //商家全选与取消选择
    public ServerResponse<CartTemVo> selectionByShop(Integer userId, Integer shopId, Boolean shopIsCheck) {
        if (shopIsCheck) {
            cartMapper.shopCheckedProduct(userId, shopId);
        } else {
            cartMapper.shopUnCheckedProduct(userId, shopId);
        }
        return selectCartProducts(userId);
    }

    //查询购物车产品列表
    public ServerResponse<CartTemVo> selectCartProducts(Integer userId) {

        Boolean allCheck = true;
        CartTemVo cartTem = new CartTemVo();
        List<ShopVo> shopVos;
        //总价
        BigDecimal cartTotalPrice = new BigDecimal(0.0);
        try {
            shopVos = cartMapper.selectShopIdsByUserId(userId);
        } catch (Exception e) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);
        }
        if (shopVos != null && shopVos.size() != 0) {
            //return  ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(),ResponseCode.CART_ISEMPTY.getDesc(),cartTem);
            for (ShopVo shop : shopVos) {
                Boolean shopCheck = true;
                List<CartProductVo> cartList = null;
                try {
                    cartList = cartMapper.selectCartShopUserId(userId, shop.getShopId());
                } catch (Exception e) {
                    return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);
                }
                if (null == cartList) {
                    return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);

                }
                BigDecimal shopTotal = new BigDecimal(0.0);
                BigDecimal shopWeight = new BigDecimal(0.0);
                //遍历商家下的产品
                for (CartProductVo cartProduct : cartList) {
                    Integer productId = cartProduct.getProductId();
                    MallProduct product = null;
                    if (productId != null) {
                        try {
                            product = productMapper.selectByProductId(productId);
                        } catch (Exception e) {
                            return ServerResponse.createByStatus(ResponseCode.PRODUCT_NOT_FOUND.getCode(), ResponseCode.PRODUCT_NOT_FOUND.getDesc(), cartTem);
                        }
                    }

                    if(product == null) {
                        continue;
                    }
                    if (cartProduct.getChecked() != 1) {
                        shopCheck = false;
                    }
                    String grade = cartProduct.getGrade();
                    if(grade != null){
                        if(grade.contains("定重")){
                            if(grade.contains("不")){
                                grade = "AA不定重";
                            }else {
                                grade = "AA定重";
                            }
                        }
                    }
                    cartProduct.setGrade(grade);
                    cartProduct.setProductSubtitle(product.getSubtitle());
                    cartProduct.setProductMainImage(product.getMainImage());
                    cartProduct.setProductName(product.getName());
                    cartProduct.setProductChecked(cartProduct.getChecked());
                    //设置库存
                    //cartProduct.setProductStock(product.getStock());
                    //预警库存
                    //int limitWt=(int)(product.getStock()*0.2);
                    //cartProduct.setLimitWeight(limitWt+"");
                    //如果预警小于购买重量就是超过
                    //Boolean isLmt= limitWt<cartProduct.getWeight()?true:false;
                    //cartProduct.setLimitStock(isLmt);
                    //阶段查询单价
                    //获取数量
                    MallPrice mallPrice;
                    if (null != cartProduct.getGrade() && !"".equals(cartProduct.getGrade())) {
                        try {
                            mallPrice = mallPriceMapper.selectPriceNum(productId, cartProduct.getWeight(), cartProduct.getGrade());
                        } catch (Exception e) {
                            e.printStackTrace();
                            return ServerResponse.createByStatus(300, "产品查询错误", null);
                        }
                        BigDecimal price = new BigDecimal(20.0);
                        if (mallPrice != null) {
                            //2019/1/21 合并等级问题
                            price = mallPrice.getPriceNum();
                            //return ServerResponse.createByStatus(303, "产品找不到对应的价格", null);
                        }
                        cartProduct.setProductPrice(price);
                        Double totalProductPrice = DecimalFormatUtrils.dataFomateTwo(price.multiply(cartProduct.getWeight()).doubleValue());
                        cartProduct.setProductStock(product.getStock());
                        if (cartProduct.getChecked() == 1) {
                            cartProduct.setProductTotalPrice(new BigDecimal(totalProductPrice));
                            shopWeight = shopWeight.add(cartProduct.getWeight());
                            shopTotal = price.multiply(cartProduct.getWeight());
                        }
                        cartProduct.setProductTotalPrice(new BigDecimal(totalProductPrice));

                    }
                }
                shop.setShopTotalWeight(shopWeight);
                shop.setShopTotalPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(shopTotal.doubleValue())));

                //2018/10/10
                //cartList要根据批号进行排序


                Collections.sort(cartList, new Comparator<CartProductVo>() {
                    @Override
                    public int compare(CartProductVo o1, CartProductVo o2) {

                        String[] nameO1 = o1.getProductName().split(",", -1);
                        String[] nameO2 = o2.getProductName().split(",", -1);
                        Integer t = nameO1[2].compareTo(nameO2[2]);
                        return t;
                    }
                });
                shop.setCartProductVoList(cartList);
                cartTotalPrice = cartTotalPrice.add(shopTotal);
                shop.setShopIsCheck(shopCheck);
                if (!shop.getShopIsCheck()) {
                    allCheck = false;
                }
            }

            cartTem.setShops(shopVos);
            cartTem.setAllChecked(allCheck);
            cartTem.setCartTotalPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(cartTotalPrice.doubleValue())));


        }
        return ServerResponse.createBySuccess(cartTem);
    }

    //查询购物车已选中产品列表
    public ServerResponse<CartTemVo> selectCheckedCartProducts(Integer userId) {
        Boolean allCheck = true;
        CartTemVo cartTem = new CartTemVo();
        List<ShopVo> shopVos;
        //总价
        BigDecimal cartTotalPrice = new BigDecimal(0.0);
        try {
            shopVos = cartMapper.selectCheckedShopIdsByUserId(userId);
        } catch (Exception e) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);
        }
        if (shopVos == null) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);

        }
        for (ShopVo shop : shopVos) {
            Boolean shopCheck = true;
            List<CartProductVo> cartList = null;
            try {
                cartList = cartMapper.selectCheckedCartShopUserId(userId, shop.getShopId());
            } catch (Exception e) {
                return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);
            }
            if (null == cartList) {
                return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), cartTem);

            }
            BigDecimal shopTotal = new BigDecimal(0.0);
            BigDecimal shopWeight = new BigDecimal(0.0);
            //遍历商家下的产品
            for (CartProductVo cartProduct : cartList) {
                Integer productId = cartProduct.getProductId();
                MallProduct product = null;
                if (productId != null) {
                    try {
                        product = productMapper.selectByProductId(productId);
                    } catch (Exception e) {
                        return ServerResponse.createByStatus(ResponseCode.PRODUCT_NOT_FOUND.getCode(), ResponseCode.PRODUCT_NOT_FOUND.getDesc(), cartTem);
                    }
                }
                if (cartProduct.getChecked() != 1) {
                    shopCheck = false;
                }
                cartProduct.setProductSubtitle(product.getSubtitle());
                cartProduct.setProductMainImage(product.getMainImage());
                cartProduct.setProductName(product.getName());
                cartProduct.setProductChecked(cartProduct.getChecked());
                //设置库存
                //cartProduct.setProductStock(product.getStock());
                //预警库存
                //int limitWt=(int)(product.getStock()*0.2);
                //cartProduct.setLimitWeight(limitWt+"");
                //如果预警小于购买重量就是超过
                //Boolean isLmt= limitWt<cartProduct.getWeight()?true:false;
                //cartProduct.setLimitStock(isLmt);
                //阶段查询单价
                //获取数量
                MallPrice mallPrice;
                if (null != cartProduct.getGrade() && !"".equals(cartProduct.getGrade())) {
                    try {
                        mallPrice = mallPriceMapper.selectPriceNum(productId, cartProduct.getWeight(), cartProduct.getGrade());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ServerResponse.createByStatus(300, "产品查询错误", null);
                    }
                    BigDecimal price = new BigDecimal(20.0);
                    if (mallPrice != null) {
                        price = mallPrice.getPriceNum();
                        //2019/1/21 前端查询出来AA不定重，实际上只有AA7不定重，因为前端显示问题和合并问题，所以去掉限制
                       // return ServerResponse.createByStatus(303, "产品找不到对应的价格", null);
                    }
                    cartProduct.setProductStock(product.getStock());
                    cartProduct.setProductPrice(price);
                    Double totalProductPrice = DecimalFormatUtrils.dataFomateTwo(price.multiply(cartProduct.getWeight()).doubleValue());
                    cartProduct.setProductTotalPrice(new BigDecimal(totalProductPrice));
                    shopWeight = shopWeight.add(cartProduct.getWeight());
                    shopTotal = shopTotal.add(price.multiply(cartProduct.getWeight()));
                }
            }
            shop.setShopTotalWeight(shopWeight);
            shop.setShopTotalPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(shopTotal.doubleValue())));
            shop.setCartProductVoList(cartList);
            cartTotalPrice = cartTotalPrice.add(shopTotal);
            shop.setShopIsCheck(shopCheck);
            if (!shop.getShopIsCheck()) {
                allCheck = false;
            }
        }
        cartTem.setShops(shopVos);
        cartTem.setAllChecked(allCheck);
        cartTem.setCartTotalPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(cartTotalPrice.doubleValue())));
        return ServerResponse.createBySuccess(cartTem);
    }

    private ServerResponse<CartVo> getCartVoLimit(Integer userId, Integer check) {
        CartVo cartVo = new CartVo();
        List<CartProductVo> cartList = null;
        try {
            cartList = cartMapper.selectCartByUserId(userId);
        } catch (Exception e) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), null);
        }
        if (null == cartList) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), null);

        }
        List<CartProductVo> cartProductVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");

        //如果购物车不为空
        if (CollectionUtils.isNotEmpty(cartList)) {
            for (CartProductVo cartProductVo : cartList) {

                MallProduct product = new MallProduct();
                //列出购物车里所有
                if (check == UN_CHECK) {
                    product = productMapper.selectByProductId(cartProductVo.getProductId());
                }
                //列出购物车里勾选的
                else if (check == CHECK) {
                    //如果是勾选的产品记录
                    if (cartProductVo.getChecked() == 1) {
                        product = productMapper.selectByProductId(cartProductVo.getProductId());
                    } else {
                        //如果不是勾选的直接跳过
                        continue;
                    }
                }

                if (product == null) continue;

                /*CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setGrade(cartItem.getGrade());
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());
                cartProductVo.setWeight(cartItem.getWeight());


                cartProductVo.setProductMainImage(product.getMainImage());
                cartProductVo.setProductName(product.getName());
                cartProductVo.setProductSubtitle(product.getSubtitle());
                cartProductVo.setProductStatus(product.getStatus());*/


                //阶梯状价格
                BigDecimal price = new BigDecimal(0.0);
                int productId = cartProductVo.getProductId();
                BigDecimal weight = cartProductVo.getWeight();
                String grade = cartProductVo.getGrade();
                System.out.println(productId + "+" + weight + "+" + grade);
                MallPrice mallPrice = mallPriceMapper.selectPriceNum(productId, weight, grade);

                System.out.println("price" + mallPrice.getPriceNum());
                cartProductVo.setProductPrice(mallPrice.getPriceNum());
                cartProductVo.setWeight(weight);
                cartProductVo.setProductTotalPrice(weight.multiply(mallPrice.getPriceNum()));
                //cartProductVo.setProductStock(product.getStock());
                //判断库存
                //int buyLimitCount = 0;
              /*  if(product.getStock() >= cartItem.getWeight()){
                    //库存充足的时候
                    buyLimitCount = cartItem.getWeight();
                    //cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    cartProductVo.setLimitWeight(Const.Cart.LIMIT_NUM_SUCCESS);
                }else{
                    buyLimitCount = product.getStock();
                    cartProductVo.setLimitWeight(Const.Cart.LIMIT_NUM_FAIL);
                    //购物车中更新有效库存
                    MallCart cartForWeight = new MallCart();
                    cartForWeight.setId(cartItem.getId());
                    cartForWeight.setWeight(buyLimitCount);
                    //更新数据库的接口
                    cartMapper.updateByPrimaryKeySelective(cartForWeight);
                }*/

                //根据重量计算价格
                // MallPrice mallPrice1 = mallPriceMapper.selectPriceNum(cartProductVo.getProductId(), buyLimitCount, cartProductVo.getGrade());
                // 如果没取到，使用产品列表价格
                /*if (mallPrice1.getPriceNum() == null) {
                    priceNum = product.getPrice();
                }*/
                cartProductVo.setProductChecked(cartProductVo.getChecked());

                if (cartProductVo.getChecked() == Const.Cart.CHECKED) {
                    //如果已经勾选,增加到整个的购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return ServerResponse.createBySuccess(cartVo);
    }

    private boolean getAllCheckedStatus(Integer userId) {
        if (userId == null) {
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }


    public ServerResponse addCartByOrderNo(Integer userId, Long orderNo) {

        //先更新购物车选择清空
        int status = 0;
        cartMapper.updateCheckStatusWithUserId(userId, status);


        //然后把当前订单的产品都勾选

        List<MallOrderItem> orderItemList = mallOrderItemMapper.selectAllByOrderNo(orderNo);
        int isChecked = 1;
        for(MallOrderItem mallOrderItem : orderItemList){
            add(userId, mallOrderItem.getProductId(), mallOrderItem.getGrade(), mallOrderItem.getQuantity());
            cartMapper.updateCheckByProduct(mallOrderItem.getProductId(), isChecked, userId);
        }

        return ServerResponse.createBySuccess();
    }
}
